from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
import re
from django.conf import settings
from django.core.cache import cache

class RbacMiddleware(MiddlewareMixin):
    def process_request(self,request):
        current_url = request.path_info + request.method.lower()
        print('rbac valid 美女西行漫记', request.path_info)
        valid_url_temp = ''
        print('current_url',current_url)
        # print('rbac request method', request.method)
        for valid_url in settings.VALID_URL_LIST:

            if '.*' in valid_url and not current_url.startswith('/api/v1'):
                print('* valid_url',valid_url)
                return None
            if re.match('^%s$' % valid_url,current_url):
                return None
            else:
                #print('111 current_url',valid_url, current_url)
                continue
                # if len(valid_url.split('/') == 5):
                #     print('rbac menus etc', current_url)
                #     return None
                # else:
                #     print('rbac another',current_url)
                #     break
        # permission_list = request.session.get(settings.PERMISSION_SESSION_KEY)
        # print('-->permission_list1',permission_list)
        # if not permission_list:
        #     return HttpResponse('未获取到用户权限信息，请登录!')

        # flag = False
        # for url in permission_list:
        #     reg = '^%s$' % url
        #     if re.match(reg,current_url):
        #         flag = True
        #         break
        # if not flag:
        #     return HttpResponse('无权访问')
        print('meow~')
        temp_url_list = current_url.split('/')[3:]
        print('222222222222222222222', temp_url_list)
        try:
            if temp_url_list[1].isnumeric():
                if len(temp_url_list) == 4:
                    current_url_temp = '/%s/%s/%s' % (temp_url_list[0], temp_url_list[2], temp_url_list[3])
                elif len(temp_url_list) == 5:
                    current_url_temp = '/%s/%s/%s' % (temp_url_list[0], temp_url_list[2], temp_url_list[4])
                else:
                    current_url_temp = '/%s/%s' % (temp_url_list[0], temp_url_list[2])
            elif len(temp_url_list) == 3:
                current_url_temp = '/%s/%s/%s' % (temp_url_list[0], temp_url_list[1], temp_url_list[2])
            #['categories', 'attributes', '7', 'delete']
            elif len(temp_url_list) == 4 and temp_url_list[2].isnumeric():
                current_url_temp = '/%s/%s/%s' % (temp_url_list[0], temp_url_list[1], temp_url_list[3])
            else:
                current_url_temp = '/%s/%s' %(temp_url_list[0],temp_url_list[1])
            # else:
            #     current_url_temp = current_url.replace('/api/v1','')
        except Exception as e:
            print('111 eeeeee', e)
            return HttpResponse('url不合法')
        permission_list = cache.get('permission_list')
        # permission_list.append('/menus/')
        # permission_list.append('/role_display/')
        # permission_list.append('/rights/tree/')
        # permission_list.append('/roles/1/rights/')
        print('-->permission_list1',permission_list)
        if not permission_list:
            return HttpResponse('未获取到用户权限信息，请登录!')
        flag = False
        print('current_url_temp', current_url_temp)
        for url in permission_list:
            reg = '^%s$' % url
            if re.match(reg, current_url_temp):
                # print('current_url_temp',current_url_temp)
                flag = True
                break
        if not flag:
            return HttpResponse('没有权限')
    # def process_response(self,request,response):
    #     # 允许跨域请求的地址 (*代表所有地址)
    #     print('response',response)
    #     response['Access-Control-Allow-Origin'] = "http://127.0.0.1:8080"
    #     # 允许跨域请求的类型
    #     response['Access-Control-Allow-Headers'] = "X-Requested-With,Content-Type"
    #     # 允许跨域请求的方式
    #     response['Access-Control-Allow-Methods'] = "PUT,POST,GET,DELETE,OPTIONS"
    #     # 允许跨域请求携带cookie
    #     response['Access-Control-Allow-Credentials'] = "true"
    #
    #     return response
